import React from 'react'
// ===================================================================== Temp
import SearchForm from '#cpt/temp/SearchForm'
import Table from '#cpt/temp/Table'
import Controls from '#cpt/temp/Controls'
import SpecCode from '#tp/specCode'
// ===================================================================== global declare
const { $fn, $Lazy, $http } = window
// ===================================================================== private component
const Box 				= $Lazy.load(()=>import('#tp/box/box'))
const $cache 			= $Lazy.file(()=>import('#private/cache-api'))
const $time 			= $Lazy.file(()=>import('@com/utils/time'))
const InputDetail		= $Lazy.state(()=>import('./input-detail'))
const AlreadyEntryTable	= $Lazy.state(()=>import('./already-entry-table'))
const ImgEdit 			= $Lazy.state(()=>import('./img-edit'))
// ===================================================================== Data
const auditStatus = [{name:'审核未通过',value:-1},{name:'待完善',value:0},{name:'待审核',value:1},{name:'审核通过',value:2}]
// ===================================================================== component
class Index extends React.Component{
	state = {
		data:[],
		pag: {},
		// 搜索表单列表
		forms: [
			{ label: '医院名称',	name: 'hospital_id',			type:'select',	loading:true,	onValue: ({rows})=>{ this.model.hosp_name=rows?.name }},
			{ label: '条码号',	name: 'spec_code', 	value:'' },
			{ label: '病人姓名',	name: 'patient_name' },
			{ label: '接收时间',	names: ['start_date', 'end_date'], 	type:'date-range', 	loading:true },
		],
		selectedKeys: [],
		img_url:'',	//查看图片的url
		tabsData: []
	}
	model = {}
	bcClass = false
	entry = false
	componentDidMount(){
		this.getSelect()
		const {spec_code} = $fn.query()
		const { forms } = this.state
		if(spec_code){
			this.model.spec_code = this.spec_code = spec_code
			forms[1].value = spec_code
		}
		this.status = this.props.status
		this.Fetchs()	
	}
	
	Fetchs = () => {
		this.onTime()
		if (this.status !==3) {
			this.entryTableFetch()
		}
	}
	onTime = () => {
		$time.then(f=>{
			const arr = f.duration['2-0-24']()
			this.resetModel = { start_date: arr[0], end_date: arr[1], 'jz-time':arr }
			this.model = {...this.model,...this.resetModel}
			this.fetch().then(data=>{
				if($fn.hasArray(this.state.data)){
					if(+this.status===3 && this.model.spec_code && this.spec_code){
						this.setState({selectedKeys:[data[0].uuid]})
						this.onRow(this.state.data[0].spec_code)
					}
				}
			})
		})
	}
	// 获取下拉数据
	getSelect = () => {
		const { forms } = this.state
		
		$cache.then( async f => {
			$fn.setRow( forms, 'hospital_id', await f.getCache({ api:'hospital' }) )
			this.setState({ forms })
		})
	}
	// paging
	fetch = () => $fn.fetch.call(this,'spec-case-info/index', { param: {double_status: this.status} })
	
	// 表单
	cols = [
		{ title: '申请单条码',	dataIndex: 'spec_code', 		...SpecCode(),	sorter:true },
		{ title: '送检单位', 	dataIndex: 'hosp_name', 		width: 200 },
		{ title: '受检人姓名',	dataIndex: 'patient_name', 		...$fn.table.name },
		{ title: '性别',		dataIndex: 'sex_name',			...$fn.table.sex },
		{ title: '年龄',		dataIndex: 'age', 				...$fn.table.age },
		{ title: '受检人电话', 	dataIndex: 'patient_phone', 	...$fn.table.phone },
		{ title: '证件类型', 	dataIndex: 'card_type_name', 	...$fn.table.card_type },
		{ title: '证件号', 		dataIndex: 'card_no', 			...$fn.table.idcard },
		{ title: '送检科室', 	dataIndex: 'department_name', 	width: 90 },
		{ title: '送检医生', 	dataIndex: 'doctor', 			width: 90 },
		{ title: '医生电话', 	dataIndex: 'doctor_phone', 		...$fn.table.phone },
		{ title: '采集时间', 	dataIndex: 'coll_time', 		...$fn.table.time },
		{ title: '审核状态', 	dataIndex: 'status', 			width: 120,	render: text => $fn.getState(auditStatus,text) },
	]
	
	controls = () => {
		return [
			Controls.back.call(this,{refresh:true, refreshName:'errorRefresh'} ),   														// 返回
		]
		
	}
	
	// 双录入,两次录入不一样时,有差异的地方加背景颜色  2022/5/25 --马婷
	// 比较差异，添加背景色
	setDiffClass = () => {
		if(this.bcClass){
			const leftValue = this.inputDetailRef1.formRef.getValue()
			const rightValue = this.inputDetailRef2.formRef.getValue()
			const { formData: f1 } = this.inputDetailRef1.state
			const { formData: f2 } = this.inputDetailRef2.state
			for (const key in leftValue){
				if(leftValue[key] !== rightValue[key]){
					const itemclass1 = key==='spec_code'?'doubleInfoSpec bcred':'bcred'
					$fn.setClassName(f1,key,itemclass1)
					$fn.setClassName(f2,key,itemclass1)
				}else{
					const itemclass2 = key==='spec_code'?'doubleInfoSpec':''
					$fn.setClassName(f1,key,itemclass2)
					$fn.setClassName(f2,key,itemclass2)
				}
			}
			this.inputDetailRef1.setState({formData: f1})
			this.inputDetailRef2.setState({formData: f2})
		}
	}
	
	// 初始化 清掉背景色
	clearClassName = () => {
		if(this.inputDetailRef1 && this.inputDetailRef1.formRef){
			const leftValue = this.inputDetailRef1.formRef.getValue()
			const { formData: f1 } = this.inputDetailRef1.state
			const { formData: f2 } = this.inputDetailRef2.state
			for (const key in leftValue){
				const itemclass2 = key==='spec_code'?'doubleInfoSpec':''
				$fn.setClassName(f1,key,itemclass2)
				$fn.setClassName(f2,key,itemclass2)
			}
			this.inputDetailRef1.setState({formData: f1})
			this.inputDetailRef2.setState({formData: f2})
		}
	}
	
	// 表格的点击事件
	onRow = (spec_code)=> {
		this.bcClass = false
		this.entry = false
		this.clearClassName()
		$http.submit(this,'spec-case-info/infoDoubleEntry',{ param:{spec_code}}).then(data=>{
			// 如果有值传入
			if ($fn.hasArray(data)) {
				if(data[1]) {
					if(data[1].double_status && +data[1].double_status ===2){
						this.inputDetailRef2.setInitValue(data[1])
						this.inputDetailRef1.setInitValue(data[0])
					}else{
						this.inputDetailRef1.setInitValue(data[1])
						this.inputDetailRef2.setInitValue(data[0])
					}
					this.bcClass = true
					this.setDiffClass()
				}else{
					if(data[0].double_status && +data[0].double_status ===2){
						this.inputDetailRef2.setInitValue(data[0])
						this.inputDetailRef1.setInitValue({})
					}else{
						this.inputDetailRef1.setInitValue(data[0])
						this.inputDetailRef2.setInitValue({})
					}
				}
			} else {
				this.inputDetailRef1.setInitValue(data)
				this.inputDetailRef2.reset()
			}
		}).catch(()=>{
			this.inputDetailRef1?.reset()
			this.inputDetailRef2?.reset()
		})
	}
	
	clearSelect = () => {
		this.entry = false
		this.setState({selectedKeys:[]})
	}
	// 待录入表格点击行
	entryRow = (uuid) => {
		this.bcClass = false
		this.clearClassName()
		$http.submit(this,'spec-case-info/info',{ param:{uuid,double_status:this.status}}).then(data=>{
			if($fn.hasObject(data)){
				const d = $fn.local('double-entry-defaults') || {}
				if(+this.status === 1){
					this.inputDetailRef1.setInitValue({...data, ...d} )
				}else if(+this.status === 2){
					this.inputDetailRef2.setInitValue({...data, ...d})
				}
			}
		}).catch(()=>{
			this.inputDetailRef1?.reset()
			this.inputDetailRef2?.reset()
		})
	}
	entryTableFetch = (savePage) => {
		if (this.status !==3) {
			clearInterval(this.timer)
			this.timer = setInterval(() => {
				if (this.entryTableRef && this.searchFormRef) {
					clearInterval(this.timer)
					const searchForm = this.searchFormRef.getValue()
					const {start_date,end_date,hosp_name} = this.model
					const { sort_type, sort, current } = this.entryTableRef.model
					this.entryTableRef.model = {...searchForm, start_date, end_date, double_status:+this.status, sort_type,sort,hosp_name}
					if(savePage){
						this.entryTableRef.model.current = current
					}
					this.entryTableRef.fetch()
				} 
			}, 200)
		}
		
	}
	formReset = () => {
		this.searchFormRef.form.resetFields()
		$time.then(f=>{
			const arr = f.duration['2-0-24']()
			this.resetModel = { start_date: arr[0], end_date: arr[1], 'jz-time':arr }
			this.model = $fn.copy(this.resetModel)
			this.searchFormRef.setValue(this.resetModel)
			this.tableFetch()
		})
		this.clearClassName()
		this.inputDetailRef1.reset()
		this.inputDetailRef2.reset()
	}
	
	onRefresh = () => {
		if(this.entry){
			this.fetch().then(()=>{
				const rows = this.state.data[this.index]
				if(rows){
					this.setState({selectedKeys:[rows.uuid]})
					this.entryRow(rows.uuid,true)
				}
			})
		}else{
			this.fetch()
		}
		this.entryTableFetch(true)
	}
	onRefresh1 = () => {
		this.fetch().then(()=>{
			const rows = this.state.data[this.index]
			if(rows){
				this.setState({selectedKeys:[rows.uuid]})
				this.onRow(rows.spec_code)
			}
		})
	}
	
	tableFetch = () => {
		this.fetch()
		this.entryTableFetch()
	}
	
	// 双录入调整，分别显示第一次录入，第二次录入 2022/6/17  --马婷
	render(){
		return (
			<>
				{/* 搜索 */}
				{ SearchForm.call(this, {timeStr:'2-0-24',
					onSubmit:() => {
						this.model.current=1
						this.tableFetch()
					},
					onReset: () => this.formReset()
				})}
				{/* 表格 */}
				{+this.status===3?
					<div className='fx h ex'>
						<div className='fx rel ex'>
							{ Table.call(this, { type: 1,sort: true,
								onRow: ({spec_code},index) => {
									this.index = index
									this.onRow(spec_code)
								},
							} )}
						</div>
						<InputDetail width={420} title='第一次录入' type={2} input_status={1} status={this.props.status} 
							setDiffClass={this.setDiffClass} 
							onRef={ ref => this.inputDetailRef1 = ref } 
							onRefresh={ this.onRefresh1 }
							previewImage = {(img_url)=>{
								this.setState({img_url})
							}}
						/>
						<InputDetail  width={420} title='第二次录入' type={2} input_status={2} status={this.props.status} 
							setDiffClass={this.setDiffClass} 
							onRef={ ref => this.inputDetailRef2 = ref } 
							onRefresh={ this.onRefresh1 } 
							previewImage = {(img_url)=>{
								this.setState({img_url})
							}}
						/>
					</div>:
					<div className='fx h'>
						{/* 表格 */}
						<div className='h fx ex rel'>
							<Box title="待录入" className='ex' flex contentClassName='rel fv pt10'>
								{ Table.call(this, { type:1, sort: true,
									onRow: ({uuid},index) => {
										this.entryRow(uuid)
										this.entryTableRef.clearSelect()
										this.index = index
										this.entry = true
									},
								} )}
							</Box>
							<Box title="已录入" className='ex' flex contentClassName='rel fv pt10'>
								<AlreadyEntryTable onRef={ ref => this.entryTableRef = ref } status = {this.props.status} 
									onFetch={() => this.entryTableFetch()} 
									onRow={this.onRow} 
									clearSelect={this.clearSelect} 
								/>
							</Box>
						</div>
						<div className='h' style={{display:+this.props.status===1?'block':'none'}}>
							<InputDetail title='第一次录入' type={1} input_status={1} status={this.props.status} code='F2'
								setDiffClass={this.setDiffClass} onRef={ ref => this.inputDetailRef1 = ref } 
								previewImage = {(img_url)=>{
									this.setState({img_url})
								}}
								onRefresh={this.onRefresh}
								entry={this.entry}
							/>
						</div>
						<div className='h fx' style={{display:+this.props.status===2?'block':'none'}}>
							<InputDetail title='第二次录入' type={1} input_status={2} status={this.props.status} code='F7'
								setDiffClass={this.setDiffClass} onRef={ ref => this.inputDetailRef2 = ref } 
								previewImage = {(img_url)=>{
									this.setState({img_url})
								}}
								onRefresh={this.onRefresh} 
								entry={this.entry}
							/>
						</div>
					</div>
				}
				<div style={{minHeight: 245, maxHeight: 245}}>
					<ImgEdit noBg src={this.state.img_url} doubleClick/>
				</div>
			</>
		)
	}
}

export default Index